var express = require("express");
var router = express.Router();
const { v4: uuidv4 } = require('uuid');
const db = require("../db/index");
// 用这个包来生成 Token 字符串
const jwt = require("jsonwebtoken");
// 导入配置文件
const config = require("../config");
// 分页查询学员列表
router.get('/userList',function(req,res,next){
    // 获取参数   当前页码   当前每页数据量
  let pageNumber = req.query.pageNumber
  // let pageSize = parseInt(req.body.pageSize)
  let pagesize = req.query.pagesize - 0
 // 求得sql语句中的参数
 console.log(pageNumber,pagesize);
//  if(!pageNumber) pageNumber=1
//  if(!pagesize) pagesize=6
 console.log(pageNumber,pagesize);
  let start = (pageNumber - 1) * pagesize
  // sql语句
  let sql = "select * from user limit ?, ?"
  let sqlParam = [start, pagesize]
  let sqlCount = "select count(*) from user"

  var count = 0
  // 执行查询
  db.query(sqlCount, null, (err, result) => {
    // 得到总记录数
    count = result[0]["count(*)"]
   
  })

  db.query(sql, sqlParam, (err, result) => {
    if (err) {
      res.send({
        code:0,
        message: err.message,
        ok:true
      })
    } else {
      res.send({
        code:200,
        message: "请求成功",
        ok: true,
        totalCount: count,
        data:result,
        total:count
      })
    }
  })

})
// 新增学员
router.post('/addStudent',function(req,res,next){
    // console.log(req.body);
    let info = req.body
    let token = req.headers.token
    
    jwt.verify(token, config.jwtSecretKey, function (err, result) {
        // console.log(result);
        if(!info.username || !info.password)  res.send({code:0,message:'密码和用户名不能为空!'})
        if(result.role == 'user'){
            res.send({code:0,message:'您的权限不够'})
        }else{
            const sql = `select *from user where username=?`
            db.query(sql,info.username,function(err,results){
                if(err)  res.send({code:0,message:err.message})
                if(results.length>0)  res.send({code:0,message:'该用户已经注册'})
                const sql1 = `insert into user set ?`
                let ID = uuidv4()
               ID = ID.replace(/-/g, '')
                db.query(sql1 , {
                    id:ID,
                    username: info.username,
                    password: info.password,
                    nickname: info.nickname,
                    phone: info.phone,
                    date:info.date,
                    gender:info.gender,
                    age:info.age,
                    photo:'https://www.qqkw.com/d/file/p/2022/12-08/da7df62bf2d7218e76cb01da67e68e30.jpg',
                    role:'user'
                  },function(err,data){
                    if(err)  res.send({code:0,message:err.message})
                    res.send({code:200,message:'添加成功！'})
                  })
                
            })
        }
      });
})
// 删除用户
router.post('/deleteStudent',function(req,res,next){
    let token = req.headers.token
    let id = req.query.id
    jwt.verify(token, config.jwtSecretKey,function(err,data){
        if(data.role == 'user'){
            res.send({code:0,message:'您的权限不够'})
        }else{
            const sql = 'delete from user where id=?'
            db.query(sql,id,function(err,result){
                if(err)  res.send({code:0,message:err.message})
                res.send({code:200,message:'删除成功！'})
            })
        }
    })

})

// 修改选中用户信息
router.post('/updateStudent',function(req,res,next){
    let token = req.headers.token
    let info = req.body
    console.log(info);
    jwt.verify(token, config.jwtSecretKey,function(err,data){
        if(err) res.send({code:0,message:err.message})
        if(data.role!=='admin')  res.send({code:0,message:'你没有权限做此操作!'})
        console.log(data);
        const sql = `update user set username=?,nickname=?,password=?,age=?,gender=?,date=? where id=? `
        db.query(sql,[info.username,info.nickname,info.password,info.age,info.gender,info.date,info.id],function(err,result){
          if(err)  res.send({code:0,message:err.message})
          res.send({code:200,message:'修改成功!'})
        })
    })
})

// 查询当前用户的信息
router.get('/getStudentInfo',function(req,res,next){
    console.log(req.query);
    let id = req.query.id
    const sql = `select * from user where id=?`
    db.query(sql,id,function(err,results){
        if(err) res.send({code:0,message:err.message})
        res.send({code:200,message:'查询成功',data:results[0]})
    })
})
// 查询用户预约练车
router.get('/getPractice',function(req,res,next){
  console.log(req.query);
  let id = req.query.nickname
  const sql = `select * from practice where nickname=?`
  db.query(sql,id,function(err,results){
      if(err){return res.send({code:0,message:err.message})} 
      console.log(results);
      res.send({code:200,message:'查询成功',data:results})
  })
})
// 查询用户预约考试
router.get('/getExam',function(req,res,next){
  console.log(req.query);
  let id = req.query.nickname
  const sql = `select * from userexam where nickname=?`
  db.query(sql,id,function(err,results){
      if(err){return res.send({code:0,message:err.message})} 
      res.send({code:200,message:'查询成功',data:results})
  })
})

// 学员模糊查询
router.post('/search',function(req,res,next){
  let username  = req.body.username
  let nickname  = req.body.nickname
  let phone  = req.body.phone
  console.log(req.body);
  const sql =  `SELECT * FROM user where username like '%${username}%' or nickname like '%${nickname}%' or phone like '%${phone}%'`
  db.query(sql,function(err,results){
    if(err) {return res.send({code:0,message:err.message})} 
    
    res.send({code:200,message:'查询成功!',data:results})
  })
})



module.exports = router;